package com.xique.park.service.biz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.bean.domain.BaseUser;
import com.xique.park.bean.domain.User;
import com.xique.park.service.biz.service.IUserAndBaseUserBizService;
import com.xique.park.service.service.IBaseUserService;
import com.xique.park.service.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author caogq
 */
@Service
public class UserAndBaseUserBizServiceImpl implements IUserAndBaseUserBizService {
    @Autowired
    private IBaseUserService baseUserService;

    @Autowired
    private IUserService userService;

    @Override
    public BaseUser userAddOrGetBaseUser(BaseUser baseUser,String orign) {
        if (StrUtil.isEmpty(baseUser.getUserName())){
            return null;
        }
        String cellphone = baseUser.getCellphone();
        //1、手机号为空，新增用户
        if (StrUtil.isEmpty(cellphone)){
            baseUser.setRemark(orign+",新增车辆用户-无手机号创建C端用户");
            baseUserService.insertBaseUser(baseUser);
            return baseUser;
        }

        //2、手机号不为空，已注册,返回已有用户
        List<BaseUser> baseUsers = baseUserService.selectBaseUserByPhone(cellphone);
        if (!baseUsers.isEmpty()){
            return baseUsers.get(0);
        }

        //3、手机号不为空，手机号未注册，新增用户
        baseUser.setRemark(orign + "新增车辆用户-有手机号创建C端用户");
        baseUserService.insertBaseUser(baseUser);

        return baseUser;
    }

    @Override
    public AjaxResult addUser(User user, String orign) {
        // 1、校验手机号重复
        if (!StrUtil.isEmpty(user.getPhone())) {
            User search = new User();
            search.setParkId(SecurityUtils.getParkId());
            search.setPhone(user.getPhone());
            search.setDelFlag(0);
            List<User> users = userService.selectUserList(search);
            if (!users.isEmpty()) {
                return AjaxResult.error("手机号已存在，请重新输入或选择用户");
            }
        }
        // 2、基础用户新增
        BaseUser baseUser = OrikaUtil.convert(user, BaseUser.class);
        baseUser.setCellphone(user.getPhone());
        BaseUser addBaseUser = userAddOrGetBaseUser(baseUser,orign);

        // 2、项目用户新增
        user.setBaseUserId(addBaseUser.getId());
        user.setParkId(SecurityUtils.getParkId());
        int i = userService.insertUser(user);

        return i > 0 ? AjaxResult.success(user) : AjaxResult.error();
    }

    @Override
    public AjaxResult updateUser(User updateUser, String orign) {
        // 1、校验手机号重复
        if (StrUtil.isNotEmpty(updateUser.getPhone())) {
            User search = new User();
            search.setParkId(SecurityUtils.getParkId());
            search.setPhone(updateUser.getPhone());
            search.setDelFlag(0);
            List<User> users = userService.selectUserList(search);
            if (!users.isEmpty() && !users.get(0).getId().equals(updateUser.getId()) ) {
                return AjaxResult.error("手机号已存在！");
            }
        }
        //通过id查出数据库中的项目用户信息
        updateUser.setParkId(SecurityUtils.getParkId());
        User user = userService.selectUserById(updateUser.getId());
        Long baseUserId = user.getBaseUserId();
        BaseUser baseUser = OrikaUtil.convert(updateUser, BaseUser.class);
        baseUser.setCellphone(updateUser.getPhone());
        baseUser.setId(user.getBaseUserId());

        //2、如果项目用户的baseUserId为空的话，创建或者查询baseUser，并绑定
        if (baseUserId == null) {
            BaseUser addBaseUser = userAddOrGetBaseUser(baseUser,"[PC车辆用户修改用户]");
            updateUser.setBaseUserId(addBaseUser.getId());
            userService.updateUser(updateUser);
            return AjaxResult.success();
        }

        //3、项目用户已经绑定过C端用户处理：手机号变更需要换绑
        BaseUser beforeUpdateBaseUser = baseUserService.selectBaseUserById(baseUser.getId());
        if (StrUtil.isNotEmpty(updateUser.getPhone()) && !StrUtil.equals(updateUser.getPhone(), beforeUpdateBaseUser.getCellphone())) {
            //手机号有变更
            List<BaseUser> newPhoneBaseUsers = baseUserService.selectBaseUserByPhone(updateUser.getPhone());
            if (newPhoneBaseUsers.isEmpty()) {
                //新手机号不存在baseUser
                baseUserService.insertBaseUser(baseUser);
                updateUser.setBaseUserId(baseUser.getId());
            } else {
                //新手机号已经存在baseUser，给当前用户换绑
                updateUser.setBaseUserId(newPhoneBaseUsers.get(0).getId());
            }
        }

        //4、更新用户tUser
        userService.updateUser(updateUser);

        return AjaxResult.success();
    }

    @Override
    public User addUserNoCheck(User user, String orign) {
        // 2、基础用户新增
        BaseUser baseUser = OrikaUtil.convert(user, BaseUser.class);
        baseUser.setCellphone(user.getPhone());
        BaseUser addBaseUser = userAddOrGetBaseUser(baseUser,orign);

        // 2、项目用户新增
        user.setBaseUserId(addBaseUser.getId());
        if (user.getParkId() == null){
            user.setParkId(SecurityUtils.getParkId());
        }
        int i = userService.insertUser(user);
        return user;
    }

    @Override
    public User updateUserNoCheck(User updateUser, String origin,Long baseUserId,Boolean needJudgePhoneChange) {
        //1、通过id查出数据库中的项目用户信息
        if (baseUserId == null){
            User user = userService.selectUserById(updateUser.getId());
            baseUserId = user.getBaseUserId();
        }
        BaseUser baseUser = OrikaUtil.convert(updateUser, BaseUser.class);
        baseUser.setCellphone(updateUser.getPhone());
        baseUser.setId(baseUserId);

        //2、如果项目用户的baseUserId为空的话，创建或者查询baseUser，并绑定
        if (baseUserId == null) {
            BaseUser addBaseUser = userAddOrGetBaseUser(baseUser,"[PC车辆用户修改用户]");
            updateUser.setBaseUserId(addBaseUser.getId());
            userService.updateUser(updateUser);
            return updateUser;
        }

        //3、项目用户已经绑定过C端用户处理：手机号变更需要换绑
        if (needJudgePhoneChange){
            BaseUser beforeUpdateBaseUser = baseUserService.selectBaseUserById(baseUser.getId());
            if (StrUtil.isNotEmpty(updateUser.getPhone()) && !StrUtil.equals(updateUser.getPhone(), beforeUpdateBaseUser.getCellphone())) {
                //手机号有变更
                List<BaseUser> newPhoneBaseUsers = baseUserService.selectBaseUserByPhone(updateUser.getPhone());
                if (newPhoneBaseUsers.isEmpty()) {
                    //新手机号不存在baseUser
                    baseUserService.insertBaseUser(baseUser);
                    updateUser.setBaseUserId(baseUser.getId());
                } else {
                    //新手机号已经存在baseUser，给当前用户换绑
                    updateUser.setBaseUserId(newPhoneBaseUsers.get(0).getId());
                }
            }
        }

        //4、更新用户tUser
        userService.updateUser(updateUser);
        return updateUser;
    }
}
